package hk.hku.hooku.servlet;

import hk.hku.hooku.util.HtmlGenerator;
import hk.hku.hooku.util.SimpleMailSender;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SendResultMailServlet
 */
public class SendResultMailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String serverAddress = "hookuserver@sina.com";
	private static final String serverPass = "1111qqqq";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SendResultMailServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String proposerMail=request.getParameter("proposerMail");
		String mailsTo = request.getParameter("mailTo");
		String title=request.getParameter("title");
		String url=request.getParameter("url");
		ArrayList<String> mailsList = new ArrayList<String>();
		mailsList.add(proposerMail);
		String[] mails = mailsTo.split("[;,\n\r\t]+");
		for (int i = 0; i < mails.length; i++) {
			if(mails[i]!="");
				mailsList.add(mails[i]);
		}

		String subject="Hooku desicion of arrangement:"+title;
		String content=HtmlGenerator.toHtml(url);
		SimpleMailSender sender = new SimpleMailSender("hookuserver@sina.com",
				"1111qqqq");
		try {
			sender.send(mailsList, subject, content);
			PrintWriter writer=response.getWriter();
			writer.write("true");
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}
